import React, { useState, useRef, useCallback, useEffect } from 'react';
import { Button, Icon, message, Modal } from 'antd';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { Form } from '@ant-design/compatible';
import styles from './index.less';
import Detail from './components/Detail';
import Edit from './components/Edit';
import Add from './components/Add';
import DataPermission from './components/DataPermission';
import { getRoleList, isDisabled, deleteRole } from './service';
import AuthComponent from '@/components/Authorized/AuthComponent';

const { confirm } = Modal;

const TableList = () => {
  const [detailVisible, setDetailVisible] = useState(false);
  const [editVisible, setEditVisible] = useState(false);
  const [addVisible, setAddVisible] = useState(false);
  const [dataPermissionVisible, setDataPermissionVisible] = useState(false);
  const [selectRowId, setselectRowId] = useState('')
  const [detailItem, setDetailItem] = useState(false);
  const [editItem, setEditItem] = useState(false);
  const [editStep, setEditStep] = useState(0);
  const actionRef = useRef();
  const [height, controlH] = useState(300);
  const [isCollapse, controlC] = useState(true);
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 385);
    } else {
      controlH(document.body.clientHeight - 498);
    }
  }, [isCollapse])
  const reloadTable = useCallback(function reloadData() {
    if (actionRef.current) {
      actionRef.current.clearSelected();
      actionRef.current.reload();
    }
  }, []);

  const options = {
    changeState: {
      func: ({ status, id: roleId }) => {
        return new Promise((res, rej) => {
          confirm({
            title: '提示',
            content: '修改角色状态将影响该角色当前已选用户，是否确认修改？',
            onOk() {
              res(isDisabled({ status: { '1': '0', '0': '1' }[status], roleId }));
            },
            onCancel() {
              rej('cancel');
            },
          });
        });
      },
      callback: (_, row) => {
        message.success(row.status === '1' ? '禁用成功!' : '启用成功!');
        reloadTable();
        setDetailVisible(false);
      },
    },
    remove: {
      func: ({ id }) => {
        return new Promise((res, rej) => {
          confirm({
            title: '提示',
            content: '删除角色将影响该角色当前已选用户，是否确认删除？',
            onOk() {
              res(deleteRole({ roleId: Array.isArray(id) ? id : [id] }));
            },
            onCancel() {
              rej('cancel');
            },
          });
        });
      },
      callback: (_, row) => {
        message.success('删除成功！');
        reloadTable();
      },
    },
    edit: {
      func: (row, step) => {
        setEditStep(step);
        setEditItem(row);
        setDetailVisible(false);
        setEditVisible(true);
        return Promise.resolve(true);
      },
    },
    add: {
      func: row => {
        setAddVisible(true);
        return Promise.resolve(true);
      },
    },
    dataPermission: {
      func({ ids }) {
        console.log(ids)
        if (ids.length === 1) {
          setselectRowId(ids[0]);
          setDataPermissionVisible(true);
          return Promise.resolve(true);
        } else {
          message.info('请勾选一条数据');
          return Promise.reject(false);
        }

      },
      callback() {
      }
    }
  };

  const optionHandle = function optionHandle(key, ...rest) {
    const { func, callback = () => { } } = options[key];
    func(...rest).then(res => callback(res, ...rest));
  };

  const columns = [
    {
      title: '操作',
      valueType: 'option',
      dataIndex: 'id',
      width: 100,
      fixed: 'left',
      hideInTable: !(
        AuthComponent.getAuth('user.role.view') ||
        AuthComponent.getAuth('user.role.edit') ||
        AuthComponent.getAuth('user.role.enable_disable') ||
        AuthComponent.getAuth('user.role.remove')
      ),
      render: (text, row) => [
        <AuthComponent authCode="user.role.view">
          <Button
            onClick={() => {
              setDetailItem(row);
              setDetailVisible(true);
            }}
            type="link"
            style={{ padding: 0 }}
          >
            查看
          </Button>
        </AuthComponent>,
        <TableDropdown
          onSelect={key => optionHandle(key, row, 0)}
          menus={[]
            .concat(AuthComponent.getAuth('user.role.edit') ? [{ key: 'edit', name: '编辑' }] : [])
            .concat(
              AuthComponent.getAuth('user.role.enable_disable')
                ? [
                  {
                    key: 'changeState',
                    name: row.status === '1' ? '禁用' : '启用',
                  },
                ]
                : [],
            )
            .concat(
              AuthComponent.getAuth('user.role.remove') ? [{ key: 'remove', name: '删除' }] : [],
            )}
        />,
      ],
    },
    {
      title: '角色代码',
      dataIndex: 'code',
    },
    {
      title: '角色名称',
      dataIndex: 'name',
    },
    {
      title: '角色类型',
      dataIndex: 'competence',
      valueEnum: {
        '0': '管理员',
        '1': '普通',
        '': '全部',
      },
      width: 120,
    },
    {
      title: '用户数量',
      dataIndex: 'counts',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      valueEnum: {
        '0': '禁用',
        '1': '启用',
        '': '全部',
      },
    },
    {
      title: '角色描述',
      dataIndex: 'description',
      hideInSearch: true,
      ellipsis: true,
      width: 250,
    },
    {
      title: '创建人',
      dataIndex: 'founder',
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      hideInSearch: true,
    },
    {
      title: '最后修改人',
      dataIndex: 'modifyPerson',
    },
    {
      title: '最后修改时间',
      dataIndex: 'modifyTime',
      hideInSearch: true,
    },
  ];

  const onDetailClose = function onDetailClose() {
    setDetailVisible(false);
    setDetailItem(false);
  };

  const onEditClose = function onEditClose() {
    setEditVisible(false);
    setEditItem(false);
  };
  return (
    <section className={styles.wrapper}>
      <div className={`${styles.table} rest-pro-table-form-compact`}>
        <ProTable
          pagination={{
            showSizeChanger: true,
            showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
          }}
          className={`rest-pro-table-form-compact ${isCollapse ? 'closeRoleTable' : 'roleTable'}`}
          scroll={{ x: 1200, y: height }}
          rowSelection={{}}
          actionRef={actionRef}
          rowKey="id"
          tableAlertRender={false}
          size={'small'}
          options={{ density: false, fullScreen: true, reload: false, setting: true }}
          toolBarRender={(_, { selectedRowKeys }) =>
            [
              <Button type="primary" onClick={() => optionHandle('dataPermission', { ids: selectedRowKeys })}>
                {/* <Icon type="add" /> */}
                数据权限
              </Button>,
              <AuthComponent authCode="user.role.add">
                <Button type="primary" onClick={() => optionHandle('add')}>
                  <Icon type="add" />
                  新增
                </Button>
              </AuthComponent>,

            ].concat(
              selectedRowKeys && selectedRowKeys.length
                ? [
                  <AuthComponent authCode="user.role.remove">
                    <Button onClick={() => optionHandle('remove', { id: selectedRowKeys })}>
                      删除
                      </Button>
                  </AuthComponent>,
                ]
                : [],
            )
          }
          request={getRoleList}
          columns={columns}
          search={{
            onCollapse: val => {
              controlC(val);
            }
          }}
        />
      </div>
      {detailItem && detailVisible && (
        <Detail
          visible={detailVisible}
          onOption={optionHandle}
          onClose={onDetailClose}
          current={detailItem}
        />
      )}
      {editItem && editVisible && (
        <Edit
          visible={editVisible}
          editStep={editStep}
          data={editItem}
          onSuccess={reloadTable}
          onClose={onEditClose}
        />
      )}
      {addVisible && (
        <Add visible={addVisible} onSuccess={reloadTable} onClose={() => setAddVisible(false)} />
      )}
      {dataPermissionVisible && (
        <DataPermission
          visible={dataPermissionVisible}
          selectRowId={selectRowId}
          // onSuccess={reloadTable}
          onClose={() => setDataPermissionVisible(false)} />
      )}
    </section>
  );
};

export default Form.create()(TableList);
